package com.shop.controller;

import com.shop.pojo.Product;
import com.shop.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/shop")
public class ProductController {
    @Autowired
    @Qualifier("productServiceImpl")
    private ProductService productService;

    @RequestMapping("/product/{productId}")
    //根据productId查询单个商品
    public String queryProduct(Model model,@PathVariable("productId") int productId){
        Product product = productService.queryProductById(productId);
        System.out.println(product.getProductName());
        model.addAttribute("product",product);
        return "search";
    }

    //搜索商品
    @RequestMapping("/search")
    public String searchProducts(@RequestParam("keywords") String keywords, Model model){
        String[] arr = keywords.split("\\s+");//按所有空格分隔字符串
        Map<String,Object> params = new HashMap<>();
        params.put("keywords",arr);
        List<Product> searchList = productService.searchProducts(params);
        model.addAttribute("searchList",searchList);
        if(searchList.isEmpty()){
            model.addAttribute("err","商品不存在哦！");
        }
        return "search";
    }
}
